#include <QThread>
#include "workpiecebuff.h"
#include "mesurementinterface.h"
#include <QDebug>

WorkpieceBuff::WorkpieceBuff() : begin_(0),
                                 end_(0),
                                 m_bufferedNum_(0),
                                 m_exit_(false)
{

}

void WorkpieceBuff::SetData(const WorkpieceInfo &workpieceInfo)
{
    {
        std::unique_lock<std::mutex> lock(mutex_);
        m_notFullCv_.wait(lock, [=] { return (m_bufferedNum_ < workpieceCircularBuffer_.size());});
        workpieceCircularBuffer_[end_] = workpieceInfo;
        end_ = (end_ + 1) % workpieceCircularBuffer_.size();
        ++m_bufferedNum_;
    }
    m_notEmptyCv_.notify_one();
}

bool WorkpieceBuff::GetData(WorkpieceInfo &workpieceInfo)
{
    {
        std::unique_lock<std::mutex> lock(mutex_);
        m_notEmptyCv_.wait(lock, [=] { return (m_bufferedNum_ > 0 || m_exit_);});
        if(m_exit_) {
            return false;
        }
        workpieceInfo = workpieceCircularBuffer_[begin_];
        begin_ = (begin_ + 1) % workpieceCircularBuffer_.size();
        --m_bufferedNum_;
    }
    m_notFullCv_.notify_one();
    return true;
}

bool WorkpieceBuff::clear()
{
    std::unique_lock<std::mutex> lock(mutex_);
    workpieceCircularBuffer_.clear();
}

void WorkpieceBuff::SetSize(size_t size)
{
    std::unique_lock<std::mutex> lock(mutex_);
    workpieceCircularBuffer_.resize(size);
}

int WorkpieceBuff::Size()
{
    std::unique_lock<std::mutex> lock(mutex_);
    return m_bufferedNum_;
}

bool WorkpieceBuff::Empty()
{
    std::unique_lock<std::mutex> lock(mutex_);
    return (m_bufferedNum_ == 0);
}

void WorkpieceBuff::Exit()
{
    std::unique_lock<std::mutex> lock(mutex_);
    m_exit_ = true;
    m_notEmptyCv_.notify_all();
    m_notFullCv_.notify_all();
}
